//
//  MyCityViewController.m
//  BSLCar
//
//  Created by 梁毅 on 15/5/23.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "MyCityViewController.h"
#import "ProCitySelect.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "ProCitySelect.h"
#import "MyTableViewCell.h"

@interface MyCityViewController () <UIGestureRecognizerDelegate, CLLocationManagerDelegate, CLLocationManagerDelegate>

{
    CLGeocoder *_geocoder;
    CLLocationCoordinate2D coordinate;
    NSString *provincename;
    NSString *cityname;
    NSString *cityId;
    NSString *cellContent;
    UITableView *mtableview;
    
    BOOL exist;
    
    BOOL dingwei;
}
@property (nonatomic, retain)CLLocationManager *myLocationManager;
@property (nonatomic, retain) NSArray *proArray;
@property (nonatomic, retain) NSArray *cityArray;
@property (nonatomic, retain) NSArray *areaArray;
@property (nonatomic, retain) NSArray *popupDataArray;
@property (nonatomic, retain) UITableView *popupTableView;
@property (nonatomic, retain) UIView *popupView;
@property (nonatomic, retain) NSString *proName;
@property (nonatomic, retain) NSString *proid;
@end
@implementation MyCityViewController
- (UITableView *)initPopupTable {
    if (_popupTableView == nil) {
        _popupTableView = [[UITableView alloc] init];
        UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
        swip.direction = UISwipeGestureRecognizerDirectionRight;
        swip.delegate = self;
        [self.popupView addGestureRecognizer:swip];
        [swip release];
    }
    return _popupTableView;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
- (UIView *)initPopupView {
    if (_popupView == nil) {
        _popupView = [[UIView alloc] init];
    }
    return _popupView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"切换地区";
    
    dingwei = NO;
    exist = NO;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    cellContent = [user objectForKey:@"dingwei"];
    if ([cellContent isEqualToString:@"全国"]) {
        cellContent = @"定位失败";
    }

    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"返回";
    self.navigationItem.backBarButtonItem = item;
    [item release];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, 2, self.view.bounds.size.width, 40)];
    label.textColor = [UIColor grayColor];
    label.text = @"\t!选择城市以后会向你推送汽车信息，但是选择省份不会推送";
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:15];
    [label sizeToFit];
    [self.view addSubview:label];
    [label release];
    mtableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 42, self.view.bounds.size.width, self.view.bounds.size.height - 110) style:UITableViewStylePlain];
    mtableview.delegate = self;
    mtableview.tag = 1000;
    mtableview.dataSource = self;
    [self.view addSubview:mtableview];
    [mtableview release];
    self.proArray = [ProCitySelect selectProvince];
}
- (void)createPopupView {
    [self initPopupView];
    _popupView.frame = CGRectMake(self.view.bounds.size.width, 40, self.view.bounds.size.width - 100, self.view.bounds.size.height - 40);
    _popupView.layer.borderWidth = 1;
    _popupView.layer.borderColor = [UIColor grayColor].CGColor;
    _popupView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.popupView];
    [self createTableView];
}
- (void)createTableView {
    [self initPopupTable];
    self.popupTableView.frame = CGRectMake(0, 0, self.popupView.bounds.size.width, self.popupView.bounds.size.height);
    self.popupTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.popupTableView.delegate = self;
    self.popupTableView.dataSource = self;
    self.popupTableView.tag = 2000;
    [self.popupView addSubview:self.popupTableView];
}
- (void)swip:(UISwipeGestureRecognizer *)swip {
    if (swip.direction == UISwipeGestureRecognizerDirectionRight) {
        [UIView animateWithDuration:1 animations:^{
            _popupView.frame = CGRectMake(self.view.bounds.size.width, 40, self.view.bounds.size.width - 100, self.view.bounds.size.height - 40);
        }];
        exist = NO;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1000) {
        static NSString *identifier = @"rootcell";
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        }
        if (indexPath.section == 0) {
            cell.textLabel.text = cellContent;
            cell.imageView.frame = CGRectMake(0, 0, 15, 15);
            cell.textLabel.font = [UIFont systemFontOfSize:16];
            cell.imageView.image = [UIImage imageNamed:@"iconfont-dingwei.png"];
        }
        if (indexPath.section == 1) {
            ProvinceDBModel *model = [self.proArray objectAtIndex:indexPath.row];
            cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", model.letter, model.proName];
            cell.imageView.image = nil;
        }
        return cell;
    }
    //popup
    if (tableView.tag == 2000) {
        static NSString *identifier = @"popupCell";
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        if (indexPath.row == 0) {
            cell.textLabel.text = [NSString stringWithFormat:@"%@全省", self.proName];
        } else {
            CityDBModel *model = [self.popupDataArray objectAtIndex:indexPath.row];
            cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", model.letter, model.cityName];
        }
        return cell;
    }
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 1000) {
        return 2;
    }
    if (tableView.tag == 2000) {
        return 1;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 1000) {
        if (section == 0) {
            return 1;
        }
        if (section == 1) {
            return self.proArray.count;
        }
    }
    if (tableView.tag == 2000) {
        return self.popupDataArray.count;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1000) {
        
        if (indexPath.section == 0) {

        }
        
        if (indexPath.section == 1) {
            ProvinceDBModel *model = [self.proArray objectAtIndex:indexPath.row];
            NSMutableArray *daArray = [NSMutableArray array];
            NSArray *array = [ProCitySelect selectCity];
            for (CityDBModel *tempmodel in array) {
                if ([tempmodel.proId isEqualToString:model.proid]) {
                    [daArray addObject:tempmodel];
                }
            }
            self.popupDataArray = daArray;
            [self.popupTableView reloadData];
            if (daArray.count <= 1) {
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setObject:model.proName forKey:@"proCity"];
                [self.mydelegate chzhi:model.proName];
                [user setValue:model.proid forKey:@"cityid"];                
                [self.navigationController popToRootViewControllerAnimated:YES];
            } else {
            }
            self.proName = model.proName;
            self.proid = model.proid;
            if (!exist) {
                [self createPopupView];
                [UIView animateWithDuration:0.5 animations:^{
                    _popupView.frame = CGRectMake(100, 40, self.view.bounds.size.width - 100, self.view.bounds.size.height - 40);
                }];
                exist = YES;
            } else {
                [_popupTableView reloadData];
            }
        }
    }
    if (tableView.tag == 2000) {
        NSString *cityid = nil;
        NSString *st;
        if (indexPath.row == 0) {
            st = self.proName;
            cityid = self.proid;
        } else {
            CityDBModel *model = [self.popupDataArray objectAtIndex:indexPath.row];
            st = [NSString stringWithFormat:@"%@/%@", self.proName, model.cityName];
            cityid = model.cityId;
        }
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:st forKey:@"proCity"];
        [user setObject:cityid forKey:@"cityid"];
        [self.mydelegate chzhi:st];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 1000) {
        if (section == 0) {
            return @"当前位置";
        }
        if (section == 1) {
            return @"省份列表";
        }
    }
    return nil;
}

- (void)dingwei {
    cellContent = @"正在定位....";
    [mtableview reloadData];
    if([CLLocationManager locationServicesEnabled]) {
        if (!self.myLocationManager){
            self.myLocationManager = [[CLLocationManager alloc]init];
        }
        self.myLocationManager.delegate = self;

        //选择定位的方式为最优的状态，他又四种方式在文档中能查到
        self.myLocationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //发生事件的最小距离间隔
        self.myLocationManager.distanceFilter = 1000.0f;
        if([self.myLocationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.myLocationManager requestAlwaysAuthorization]; // 永久授权
            [self.myLocationManager requestWhenInUseAuthorization]; //使用中授权
        }
        [self.myLocationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.myLocationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [self.myLocationManager requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    coordinate = location.coordinate;//位置坐标
    //  NSLog(@"经度：%f,纬度：%f",coordinate.longitude,coordinate.latitude);
    //如果不需要实时定位，使用完即使关闭定位服务
    [self.myLocationManager stopUpdatingLocation];
    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
    //    NSLog(@"%f", coordinate.latitude);
}
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        cityname = placemark.locality;
        provincename = placemark.administrativeArea;
        cityname = [cityname substringToIndex:cityname.length - 1];
        provincename = [provincename substringToIndex:provincename.length - 1];
        
        NSArray *proArray = [ProCitySelect selectProvince];
        for (ProvinceDBModel *tempModel in proArray) {
            if ([tempModel.proName isEqualToString:provincename]) {
                cityId = tempModel.proid;
                break;
            }
        }
        BOOL isE = NO;
        NSArray *cityArray = [ProCitySelect selectCity];
        for (CityDBModel *tempModel in cityArray) {
            if ([tempModel.cityName isEqualToString:cityname] && [tempModel.proId isEqualToString:cityId]) {
                cityId = tempModel.cityId;
                isE = YES;
                break;
            }
        }
        
        if (isE) {
            provincename = [NSString stringWithFormat:@"%@/%@", provincename, cityname];
        }
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:provincename forKey:@"proCity"];
        [user setObject:cityId forKey:@"cityid"];
        [user setObject:provincename forKey:@"dingwei"];
    }];
    
    cellContent = provincename;
    [mtableview reloadData];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"地理解码错误息"
                          message:@"地理代码不能识别"
                          delegate:nil
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"全国" forKey:@"proCity"];
    [user setObject:@"0" forKey:@"cityid"];
    
    cellContent = @"定位失败, 点击重试";
    [mtableview reloadData];
    dingwei = NO;
}


- (void)back
{

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
